package org.example.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@WebServlet("/httpServletDemo4")
public class HttpServletDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决POST中文乱码问题：设置字符输入流的编码
        req.setCharacterEncoding("UTF-8");

        System.out.println("httpServletDemo4_doGet?");
        //获取所有参数的Map集合
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (String key : parameterMap.keySet()) {
            System.out.print(key + ":");
            String[] values = parameterMap.get(key);
            for (String value : values) {
                System.out.print(value + ",");
            }
            System.out.println();
        }
        //获取单个参数
        System.out.println("----------------------");
        String[] hobbies = req.getParameterValues("hobby");
        System.out.print("hobby : ");
        for (String hobby : hobbies) {
            System.out.print(hobby + ",");
        }
        System.out.println();
        System.out.println("-----------------------");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //解决GET中文乱码问题
        //GET获取参数的方式：getQueryString
        //乱码原因：tomcat进行url解码，默认字符集为ISO-8859-1
        //先把乱码数据转为字节数组，然后将字节数组转为String
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
        System.out.println("username = " + username);
        System.out.println("password = " + password);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("httpServletDemo4_doPost?");
        this.doGet(req, resp);
    }
}
